<template>
  <div class="dashboard-container">
    <div class="app-container">
      <!-- 靠右的按钮 -->
      <page-tools>
        <template v-slot:after>
          <el-button type="primary" size="small" @click="addFn"
            >添加权限</el-button
          >
        </template>
      </page-tools>
      <!-- 表格 -->
      <!-- 注意：树形表格的渲染一定需要提供树形结构的数据和唯一确定的row-key -->
      <el-table border :data="tableData" row-key="id">
        <el-table-column prop="name" align="center" label="名称" />
        <el-table-column prop="code" align="center" label="标识" />
        <el-table-column prop="description" align="center" label="描述" />
        <el-table-column align="center" label="操作">
          <template slot-scope="{ row }">
            <!-- type: 1代表菜单权限， type：2代表按钮权限 -->
            <!-- 注意： 只有菜单权限所在的行才能拥有添加功能 -->
            <el-button v-if="row.type === 1" type="text" @click="addPmsFn(row)">添加</el-button>
            <el-button type="text" @click="editFn(row)">编辑</el-button>
            <el-button type="text" @click="delFn(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增权限弹框 -->
    <addPms ref="addpms" :visible.sync="addPmsShow" @success="initData"></addPms>
  </div>
</template>

<script>
import { getPermissionApi, delPmsApi } from '@/api/permission'
import { tranListToTreeData } from '@/utils'
import addPms from './components/add-pms.vue'
export default {
  data() {
    return {
      tableData: [], // 存放权限数据，渲染表格，需要是树形结构
      addPmsShow: false // 控制新增权限弹框显示与隐藏
    }
  },
  components: {
    addPms
  },
  created() {
    this.initData()
  },
  methods: {
    // 菜单添加按钮权限
    addPmsFn(row) {
      this.$refs.addpms.pid = row.id
      this.$refs.addpms.type = '2'
      this.addPmsShow = true
    },
    // 编辑权限
    async editFn(row) {
      await this.$refs.addpms.getPmsInfo(row.id)
      this.addPmsShow = true
    },
    // 删除权限
    async delFn(row) {
      await this.$confirm('此操作将删除权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      await delPmsApi(row.id)
      this.$message.success('删除成功')
      this.initData()
    },
    // 添加权限
    addFn() {
      this.addPmsShow = true
    },
    // 初始化表格数据
    async initData() {
      const res = await getPermissionApi()
      this.tableData = tranListToTreeData(res, '0')
    }
  }
}
</script>

<style>
</style>